package org.effdom.example;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.effdom.Document;
import org.effdom.DocumentFactory;
import org.effdom.io.DocumentReader;
import org.effdom.io.DocumentWriter;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HttpDomServer implements HttpHandler {

    private final HttpServer server;

    public HttpDomServer() throws IOException {
        super();
        server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/", this);
        server.setExecutor(Executors.newCachedThreadPool());
        server.start();
    }

    public void handle(HttpExchange exchange) throws IOException {
        Headers responseHeaders = exchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/plain");
        exchange.sendResponseHeaders(200, 0);

        DocumentFactory factory = DocumentFactory.createInstance();

        DocumentReader reader = factory.createDocumentReader();
        Document doc = reader.read(exchange.getRequestBody());

        System.out.println("Received document:\n" + doc);

        DocumentWriter writer = factory.createDocumentWriter();
        writer.write(doc, exchange.getResponseBody());

        exchange.close();

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            new HttpDomServer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
